//////////////////////////////////////////////////////////////////////////
// $Id: IndexBuffer.cpp,v 1.1 2009/04/03 12:46:11 sunjun Exp $
//////////////////////////////////////////////////////////////////////////

#include "Local.h"

//////////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////////

NAMESPACE_BEGIN

//////////////////////////////////////////////////////////////////////////	

	IndexBuffer::IndexBuffer( const Context* rc ) : mHandle(NULL) 
	{
		CHECK(rc);
		mRCPtr = (Context*)rc;
	}

	IndexBuffer::~IndexBuffer() 
	{
		if((IDirect3DIndexBuffer9*)mHandle){((IDirect3DIndexBuffer9*)mHandle)->Release(); mHandle = NULL;}
	}

	//////////////////////////////////////////////////////////////////////////

	/*
	====================
	handle
	====================
	*/
	INLINE HANDLE IndexBuffer::handle() const
	{
		return mHandle;
	}

	/*
	====================
	load
	====================
	*/
	INLINE VOID IndexBuffer::load( const VOID* data, U32 count, U32 stride )
	{
		// create the index buffer
		if( mHandle == NULL )
		{			
			IDirect3DIndexBuffer9* d3d9IndexBuffer = NULL;
			HRESULT hr = ((IDirect3DDevice9*)mRCPtr->handle())->CreateIndexBuffer( count * stride, 
				D3DUSAGE_WRITEONLY, (stride==2?D3DFMT_INDEX16:D3DFMT_INDEX32), D3DPOOL_DEFAULT, &d3d9IndexBuffer, NULL );
			if( FAILED(hr) )
			{
				MAssert(VA("IndexBuffer::load : create the index buffer is failed(%s)!", DXGetErrorDescription(hr)));
			}
			mHandle = d3d9IndexBuffer;
			mCount = count;
		}
		
		// update the index buffer
		if( data )
		{
			VOID *dest;
			HRESULT hr = ((IDirect3DIndexBuffer9*)mHandle)->Lock(0, count * stride, &dest, 0);
			if( SUCCEEDED(hr) )
			{
				::memcpy(dest, data, count * stride);
				((IDirect3DIndexBuffer9*)mHandle)->Unlock();
			} 
			else 
			{
				MAssert(VA("IndexBuffer::load : lock the index buffer is failed(%s)!", DXGetErrorDescription(hr)));				
			}
		}		
	}
	
//////////////////////////////////////////////////////////////////////////

NAMESPACE_END

//////////////////////////////////////////////////////////////////////////
